package com.molichuxing.gateway.api.services.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.molichuxing.framework.dto.Paged;
import com.molichuxing.framework.dto.UploadFileRequestDto;
import com.molichuxing.framework.dto.UploadFileResponseDto;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.UploadUtil;
import com.molichuxing.gateway.api.services.BasicApiService;
import com.molichuxing.gateway.bff.basic.entity.response.InsuranceCompanyVo;
import com.molichuxing.gateway.bff.basic.entity.response.OwnershipDetailVo;
import com.molichuxing.gateway.bff.basic.entity.response.OwnershipVo;
import com.molichuxing.gateway.bff.basic.entity.response.ReceiptCompanyVo;
import com.molichuxing.gateway.bff.basic.entity.response.RegionCityVo;
import com.molichuxing.gateway.bff.basic.entity.response.SubcompanyVo;
import com.molichuxing.gateway.bff.basic.entity.response.VehicleMakeVo;
import com.molichuxing.gateway.bff.basic.entity.response.VehicleModlemakeVo;
import com.molichuxing.gateway.bff.basic.service.BasicBffService;
import com.molichuxing.gateway.bff.basic.service.FileStorageBffService;
import com.molichuxing.gateway.bff.basic.service.ReceiptCompanyBffService;
import com.molichuxing.gateway.bff.basic.service.VehicleBffService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/basic")
@Api(tags="基础数据")
public class BasicApiServiceImpl extends RootApiService implements BasicApiService {
	private static final Logger logger = LoggerFactory.getLogger(BasicApiServiceImpl.class);

	@Resource
	private BasicBffService baiscBffService;

	@Resource
	private FileStorageBffService fileStorageBffService;

	@Resource
	private VehicleBffService vehicleBffService;

	@Resource
	private ReceiptCompanyBffService receiptCompanyBffService;


	@Override
	@ApiOperation(value = "获取保险公司关系")
	@GetMapping(value = "/insurance/company")
	public ResponseResult<List<InsuranceCompanyVo>> getInsuranceCompany() {
		ResponseResult<List<InsuranceCompanyVo>> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getInsurance());
		} catch (Exception e) {
			logger.error("[getInsuranceCompany]获取保险公司关系信息异常", e);
			result.error("获取保险公司关系信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "获取省市区父子级关系")
	@ApiImplicitParam(name = "level", value = "等级，不传表示所有，1：省，2：市，3：区", required = false, dataType = "Integer")
	@GetMapping(value = "/region/getallcity")
	public ResponseResult<List<RegionCityVo>> getAllCity(@RequestParam(required = false) Integer level) {
		ResponseResult<List<RegionCityVo>> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getAllCity(level));
		} catch (Exception e) {
			logger.error("[getAllCity]获取省市区父子级别信息异常", e);
			result.error("获取省市区父子级别信息异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "获取分子公司列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "name", value = "公司简称", required = false, dataType = "String"),
			@ApiImplicitParam(name = "responsibleAccountName", value = "负责人姓名", required = false, dataType = "String"),
			@ApiImplicitParam(name = "regionId", value = "城市", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer")

	})
	@GetMapping(value = "/subcompany/list")
	public ResponseResult<Paged<SubcompanyVo>> getSubcompanyList(@RequestParam Map<String, Object> selectParams) {
		ResponseResult<Paged<SubcompanyVo>> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getSubcompanyListPage(selectParams));
		} catch (Exception e) {
			logger.error("[getSubcompanyList]获取分子公司列表异常", e);
			result.error("获取分子公司列表异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "根据分子公司id 获取分子公司详情")
	@ApiImplicitParam(name = "id", value = "分子公司id", required = true, dataType = "Integer")
	@GetMapping(value = "/subcompany/getsubcompany")
	public ResponseResult<SubcompanyVo> getSubcompanyVo(@RequestParam Integer id) {
		ResponseResult<SubcompanyVo> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getSubcompany(id));
		} catch (Exception e) {
			logger.error("[getsubcompany]根据分子公司id 获取分子公司详情异常", e);
			result.error("根据分子公司id 获取分子公司详情异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "新增分子公司")
	@PostMapping(value = "/subcompany/create")
	public ResponseResult<Boolean> createSubcompany(@RequestBody SubcompanyVo subcompanyVo) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.createSubcompany(subcompanyVo));
		} catch (Exception e) {
			logger.error("[createSubcompany]新增分子公司异常", e);
			result.error("新增分子公司异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "修改分子公司")
	@PostMapping(value = "/subcompany/modify")
	public ResponseResult<Boolean> modifySubcompany(@RequestBody SubcompanyVo subcompanyVo) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.modifySubcompany(subcompanyVo));
		} catch (Exception e) {
			logger.error("[modifySubcompany]修改分子公司异常", e);
			result.error("修改分子公司异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "获取产权方列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "pageNum", value = "页码", required = true, dataType = "Integer"),
			@ApiImplicitParam(name = "pageSize", value = "每页条数", required = true, dataType = "Integer") })
	@GetMapping(value = "/ownership/list")
	public ResponseResult<Paged<OwnershipVo>> getOwnershipListPage(@RequestParam Map<String, Object> selectParams) {
		ResponseResult<Paged<OwnershipVo>> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getOwnershipListPage(selectParams));
		} catch (Exception e) {
			logger.error("[getOwnershipListPage]获取产权方列表异常", e);
			result.error("获取产权方列表异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "新增产权方")
	@PostMapping(value = "/ownership/create")
	public ResponseResult<Boolean> createOwnership(@RequestBody OwnershipVo ownershipVo) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.createOwnership(ownershipVo));
		} catch (Exception e) {
			logger.error("[createOwnership]新增产权方异常", e);
			result.error("新增产权方异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "修改产权方")
	@PostMapping(value = "/ownership/modify")
	public ResponseResult<Boolean> modifyOwnership(@RequestBody OwnershipVo ownershipVo) {
		ResponseResult<Boolean> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.modifyOwnership(ownershipVo));
		} catch (Exception e) {
			logger.error("[modifySubcompany]修改产权方异常", e);
			result.error("修改产权方异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "根据id查询产权方详情")
	@ApiImplicitParam(name = "ownershipId", value = "产权方id", required = true, dataType = "Integer")
	@GetMapping(value = "/ownership/id")
	public ResponseResult<OwnershipDetailVo> getOwnershipById(@RequestParam Integer ownershipId) {
		ResponseResult<OwnershipDetailVo> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getOwnershipById(ownershipId));
		} catch (Exception e) {
			logger.error("[getsubcompany]根据id查询产权方详情异常", e);
			result.error("根据id查询产权方详情异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "根据省份id查询分子公司列表")
	@ApiImplicitParam(name = "provinceId", value = "省份id", required = false, dataType = "Integer")
	@GetMapping(value = "/ownership/provinceId")
	public ResponseResult<List<SubcompanyVo>> getOwnershipByProvinceId(@RequestParam(required = false) Integer provinceId) {
		ResponseResult<List<SubcompanyVo>> result = new ResponseResult<>();
		try {
			return result.success(baiscBffService.getOwnershipByProvinceId(provinceId));
		} catch (Exception e) {
			logger.error("[getsubcompany]根据id查询产权方详情异常", e);
			result.error("根据id查询产权方详情异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "查询子品牌车系车型信息")
	@GetMapping(value = "/vehicle/make")
	public ResponseResult<List<VehicleModlemakeVo>> getVehicleModlemake() {
		ResponseResult<List<VehicleModlemakeVo>> result = new ResponseResult<>();
		try {
			return result.success(vehicleBffService.getVehicleModlemakeBizDto());
		} catch (Exception e) {
			logger.error("[getVehicleModlemake]查询子品牌车系车型信息异常", e);
			result.error("查询子品牌车系车型信息异常");
		}
		return result;
	}


	@Override
	@ApiOperation(value = "获取车辆品牌列表")
	@ApiImplicitParam(name = "isMainMake", value = "是否是主品牌（ 0:否，1是）", required = true, dataType = "Integer")
	@GetMapping(value = "/vehicle/make/list")
	public ResponseResult<List<VehicleMakeVo> > getModelMakeList(@RequestParam Integer isMainMake) {
		ResponseResult<List<VehicleMakeVo> > result = new ResponseResult<>();
		try {
			return result.success(vehicleBffService.getModelMakeList(isMainMake));
		} catch (Exception e) {
			logger.error("[getsubcompany]根据id查询产权方详情异常", e);
			result.error("根据id查询产权方详情异常");
		}
		return result;
	}

	@Override
	@ApiOperation(value = "查询所有收款方信息")
	@GetMapping(value = "/receipt/company")
	public ResponseResult<List<ReceiptCompanyVo>> receiptCompany() {
		ResponseResult<List<ReceiptCompanyVo>> result = new ResponseResult<>();
		try {
			result.success(receiptCompanyBffService.getReceiptCompany());
		} catch (BizException e) {
			logger.error("[receiptCompany]获取所有收款方信息异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[receiptCompany]获取所有收款方信息异常", e);
			result.error("文获取所有收款方信息失败");
		}

		return result;
	}

	@Override
	@ApiOperation(value = "文件上传-单个")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "type", value = "文件类型（user：用户，dealer：经销商，vehicle：车辆，"
					+ "advertising：广告，accident：事故，maintenance：保养，check：车辆检验，contract：合同，invoice：发票，"
					+ "finance：财务）", required = true, dataType = "String") })
	@PostMapping(value = "/upload/{type}")
	public ResponseResult<UploadFileResponseDto> uploadFile(HttpServletRequest request, MultipartFile file,
			@PathVariable("type") String type) {
		ResponseResult<UploadFileResponseDto> result = new ResponseResult<>();
		try {
			// 查询文件存储配置
			UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig(type);
			if (uploadFileRequestDto == null) {
				result.error(ResponseCodeEnum.UPLOAD_ERROR.getCode(), "文件上传失败,不存在的文件类型");
			}
			result.success(UploadUtil.uploadFileToAll(file, uploadFileRequestDto));
		} catch (BizException e) {
			logger.error("[uploadFile]文件上传异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[uploadFile]文件上传异常", e);
			result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "文件上传失败");
		}

		return result;
	}

	@Override
	@ApiOperation(value = "文件上传-批量")
	@ApiImplicitParams({ @ApiImplicitParam(name = "type", value = "文件类型（user：用户，dealer：经销商，vehicle：车辆，"
			+ "advertising：广告，accident：事故，maintenance：保养，check：车辆检验，contract：合同，invoice：发票，"
			+ "finance：财务）", required = true, dataType = "String") })
	@PostMapping(value = "/upload/{type}/batch")
	public ResponseResult<List<UploadFileResponseDto>> uploadFileBatch(HttpServletRequest request,
			MultipartFile[] files, @PathVariable("type") String type) {
		ResponseResult<List<UploadFileResponseDto>> result = new ResponseResult<>();
		try {
			// 查询文件存储配置
			UploadFileRequestDto uploadFileRequestDto = fileStorageBffService.getFileStorageConfig(type);
			if (uploadFileRequestDto == null) {
				result.error(ResponseCodeEnum.UPLOAD_ERROR.getCode(), "文件上传失败,不存在的文件类型");
			}
			result.success(UploadUtil.uploadFileBatchToAll(files, uploadFileRequestDto));
		} catch (BizException e) {
			logger.error("[uploadFile]文件批量上传异常", e);
			result.error(e.getExceptionCode(), e.getMessage());
		} catch (Exception e) {
			logger.error("[uploadFile]文件批量上传异常", e);
			result.error(ResponseCodeEnum.UNKNOWN_ERROR.getCode(), "文件批量上传失败");
		}

		return result;
	}
}
